package com.tbit.uqbike.tergateway.gt06pkg;

import com.alibaba.fastjson.annotation.JSONField;
import com.tbit.uqbike.TerGatewayMain;
import com.tbit.uqbike.protocol.AnalyzeImpl.AProtocol;
import com.tbit.uqbike.protocol.AnalyzeImpl.Gt06DeEnCoder;
import com.tbit.uqbike.tergateway.config.TerGatewayConfig;
import com.tbit.uqbike.tergateway.data.TerGatewayData;
import com.tbit.uqbike.tergateway.entity.AConnInfo;
import com.tbit.uqbike.tergateway.pojo.TerAlarm;
import com.tbit.uqbike.util.ErrorCode;
import io.netty.buffer.ByteBuf;

import java.util.Date;
import java.util.LinkedList;

/**
 * @author MyWin E-mail:335918956@qq.com
 * @version 1.0
 * @createTime 2019-6-27 16:18
 */
public class AlarmInfo extends CommPkg {
    private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(AlarmInfo.class);
    @JSONField(name = "时间", format = "yyyy-MM-dd HH:mm:ss")
    public Date posDt;
    @JSONField(name = "卫星个数")
    public int gpsCnt;
    @JSONField(name = "经度")
    public double lon;
    @JSONField(name = "纬度")
    public double lat;
    @JSONField(name = "速度")
    public int speed;
    @JSONField(name = "状态")
    public int status;
    @JSONField(name = "方向角")
    public int dir;
    @JSONField(name = "定位方式")
    public int pointType = 0;
    @JSONField(name = "基站")
    public String cellId;

    @JSONField(name = "终端状态")
    public int terStatus;
    @JSONField(name = "电量")
    public int power;
    @JSONField(name = "GSM")
    public int gsmLevel;
    @JSONField(name = "告警码")
    public int alarmCode;
    @JSONField(name = "语言")
    public int lang;

    @Override
    public void doBusiness() {
        logger.debug(this.toString());
        // 先判断是否合法，不合法直接过滤掉不处理
        TerAlarm newInfo = getTerAlarm();
        int code = TerGatewayMain.terEvnet.terRecvNewAlarm(newInfo);
        if (code != ErrorCode.OK) {
            logger.info(String.format("由于:[%s]过滤掉告警信息:[%s]", ErrorCode.ErrorString(code), newInfo.toString()));
        } else {
            // 插入历史轨迹
            TerGatewayData.addTerHisAlarm(newInfo);
            // 推送给公共平台
            TerGatewayMain.getProducer().sendDataToQueue(TerGatewayConfig.alarmPushRouteKey, TerAlarm.getAlarmPushMsg(newInfo));
        }
    }

    private TerAlarm getTerAlarm() {
        TerAlarm terAlarm = new TerAlarm();
        // 有转换需求
        terAlarm.setAlarmType(this.alarmCode);
        terAlarm.setDt(this.posDt);
        terAlarm.setErrCode("");
        terAlarm.setMachineNO(this.mno);
        terAlarm.setAlarmExMsg("");
        terAlarm.setAlarmExCode(new LinkedList<Integer>());
        return terAlarm;
    }

    @Override
    public boolean autoRsp() {
        return true;
    }

    @Override
    public ByteBuf getRsp(AConnInfo conn, AProtocol protocol) {
        ByteBuf byteBuf = Gt06DeEnCoder.buildCommRsp(this);
        return byteBuf;
    }
}
